/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useRef, useCallback } from 'react';
import ProForm, { ProFormSelect, ProFormRadio, ProFormText } from '@ant-design/pro-form';
import { Row, Col, Form, Input } from 'antd';
import { initialValues } from './utils';
import type { ProFormInstance } from '@ant-design/pro-form';
import { getSelectTime, getOptions } from '../index.config';

const { TextArea } = Input;
const idRegExr = /[\r\n\;\,]/g;

const searchOptions = [
  { label: '订单号', value: 'orderNo' },
  { label: '运单号', value: 'waybill' },
];

const textAreaSize = {
  minRows: 5,
  maxRows: 5,
};
interface FormProps {
  onChange?: Function;
  onSubmit: Function;
  onReset: Function;
}
const getChange = (data: {
  [propName: string]: string;
}): { change: string; value: string | string[] } => {
  return {
    change: Object.keys(data)[0],
    value: Object.values(data)[0],
  };
};

const OrderFrom: React.FC<FormProps> = (props) => {
  const { onSubmit, onReset } = props;
  const [tValue, settValue] = useState<string>('');
  const [searchType, setSearchType] = useState('orderNo');
  const handleToggleSearchType = (e: any) => {
    setSearchType(e.target.value);
  };
  const formRef = useRef<ProFormInstance>();
  const [areaVerify, setAreaVerify] = useState({
    order_id: {
      validateStatus: '',
      help: '',
    },
    waybill_no: {
      validateStatus: '',
      help: '',
    },
  });
  const handleFormFieldsChange = useCallback(
    (data: any) => {
      const { value, change } = getChange(data);
      if (['order_id', 'waybill_no'].includes(change)) {
        const verifyCfg = {
          validateStatus: 'success',
          help: '单次批量查询最多支持20个运单号|订单号',
        };
        if (value.length > 20) {
          verifyCfg.validateStatus = 'error';
        }
        setAreaVerify({
          ...areaVerify,
          [change]: verifyCfg,
        });
      }
    },
    [areaVerify],
  );

  const formatData = (data: string) => {
    const idString = data.replace(idRegExr, ',');
    const ids = idString.split(',');
    const queryData = ids.filter((item: string) => !!item).join(',');
    return {
      queryData,
      len: ids.length,
    };
  };

  const handleFinish = async (values: any) => {
    if (values.orderNo) {
      const { queryData } = formatData(values.orderNo);
      values.orderNo = queryData;
    } else if (values.waybill) {
      const { queryData } = formatData(values.waybill);
      values.waybill = queryData;
    }
    onSubmit(values);
  };

  const handleReset = async () => onReset();

  return (
    <ProForm
      layout='horizontal'
      submitter={{
        searchConfig: {
          resetText: '重置',
          submitText: '查询',
        },
        resetButtonProps: {
          style: { marginLeft: 100 },
        },
      }}
      onValuesChange={handleFormFieldsChange}
      initialValues={initialValues}
      onFinish={handleFinish}
      onReset={handleReset}
      formRef={formRef}
    >
      <Row justify='space-between'>
        <Col xs={24} sm={24} md={16} lg={16} xl={16}>
          <Row justify='space-around' gutter={2}>
            <Col md={10} xl={10} xs={24} sm={24}>
              <ProFormText label='发件人手机号' name='user' placeholder='请输入发件人手机号' />
              <ProFormText label='快递员手机号' name='courier' placeholder='请输入快递员手机号' />
              <ProFormText label='受理网点' name='shop' placeholder='请输入网点名称' />
            </Col>
            <Col md={10} xl={10} xs={24} sm={24}>
              <ProFormSelect
                label='下单日期'
                options={[
                  {
                    label: '最近一个月',
                    value: '0',
                  },
                  ...getSelectTime(),
                ]}
                name='create_at'
              />
              <ProFormSelect
                label='订单状态'
                options={[
                  {
                    label: '全部',
                    value: '',
                  },
                  ...getOptions(),
                ]}
                name='status'
              />
            </Col>
          </Row>
        </Col>
        <Col xs={24} sm={24} md={8} lg={8} xl={8}>
          <ProFormRadio.Group
            radioType='button'
            fieldProps={{
              value: searchType,
              onChange: handleToggleSearchType,
            }}
            options={searchOptions}
          />
          <Form.Item
            name={searchType}
            hasFeedback
            {...areaVerify[searchType]}
            normalize={(value) => {
              const { len } = formatData(value);
              if (len > 20) {
                return tValue;
              }
              settValue(value);
              return value;
            }}
          >
            <TextArea
              autoSize={textAreaSize}
              placeholder='输入订单号/运单号（支持批量查询，单号之间换行输入，单次最多20条）'
            />
          </Form.Item>
        </Col>
      </Row>
    </ProForm>
  );
};
export default OrderFrom;
